<template>
  <div class="employees-container">
    <div class="app-container">
      <!--       <PageTools>
        <template #left>123</template>
<template #right>
          <el-button type="primary" size="small">历史归档</el-button>
          <el-button type="primary" size="small">导出</el-button>
        </template>
</PageTools> -->
      <!-- 下方表格部分 -->
      <template>
        <div class="employees-container">
          <div class="app-container">
            <page-tools>
              <template #left>
                <span>总记录数: 16 条</span>
              </template>

              <template #right>
                <el-button
                  type="warning"
                  size="small"
                  @click="$router.push('/import/index?type=employees')"
                >excel导入</el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDownload"
                >excel导出</el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="openAddDialog"
                >新增员工</el-button>
              </template>
            </page-tools>

            <el-card style="margin-top: 10px">
              <el-table v-loading="isLoading" border :data="list">
                <el-table-column
                  type="index"
                  label="序号"
                  :index="indexMethods"
                  width="100px"
                />
                <el-table-column label="姓名" prop="username" />
                <el-table-column label="头像" prop="staffPhoto">
                  <template #default="{row}">
                    <img v-imgError="defaultImg" :src="row.staffPhoto||defaultImg" alt="" class="img_box">
                  </template>
                </el-table-column>
                <el-table-column label="手机号" prop="mobile" />
                <el-table-column label="工号" prop="workNumber" />
                <el-table-column
                  label="聘用形式"
                  prop="formOfEmployment"
                  :formatter="formatterText"
                />
                <el-table-column label="部门" prop="departmentName" />
                <el-table-column label="入职时间" prop="timeOfEntry">
                  <template #default="{ row }">
                    {{ formateTime(row.timeOfEntry) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="280">
                  <template #default="{ row }">
                    <el-button v-permission="'POINT-USER-ADD'" type="text" size="small" @click="$router.push({path:`/employees/detail?id=${row.id}`})">查看</el-button>
                    <el-button type="text" size="small" @click="showRoleDialogFn(row.id)">分配角色</el-button>
                    <el-button
                      v-permission="'POINT-USER-DEKETE'"
                      type="text"
                      size="small"
                      @click="del(row.id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页组件 -->
              <div style="height: 60px; margin-top: 10px">
                <el-pagination
                  :page-size="pageSize"
                  :current-page="page"
                  :total="total"
                  layout="prev, pager, next"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-card>
            <AddEmplotee :show-dialog.sync="showDialog" />
          </div>
        </div>
      </template>
    </div>
    <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeListApi, delEmployeeApi } from '@/api/employees'
import EnumObj from '@/constant/employees'
import dayjs from 'dayjs'
import AddEmplotee from './components/add-employee.vue'
import defaultImg from '@/assets/common/bigUserHeader.png'
import AssignRole from './components/assign-role'
import { mapGetters } from 'vuex'
export default {
  name: 'Employees',
  components: {
    AddEmplotee,
    AssignRole
  },
  data() {
    return {
      page: 1,
      pageSize: 10,
      total: 0,
      list: [],
      isLoading: false,
      showDialog: false,
      defaultImg,
      showRoleDialog: false,
      userId: ''
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    /**
     * 展示分配权限弹框
     */
    showRoleDialogFn(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    /**
     * 获取员工列表
     */
    async getEmployeeList() {
      const res = await getEmployeeListApi(this.page, this.pageSize)
      const { total, rows } = res.data
      this.total = total
      this.list = rows
      // console.log(this.total, this.list, '@@@')
    },
    /**
     * 分页器点击时添加
     */
    handleCurrentChange(val) {
      this.page = val
      this.isLoading = true
      this.getEmployeeList()
      this.isLoading = false
    },
    /**
     * 每一行的行号
     */
    indexMethods(index) {
      return (this.page - 1) * this.pageSize + index + 1
    },
    formatterText(row, column, cellValue, index) {
      const res = EnumObj.hireType.find((item) => {
        return item.id === cellValue
      })
      if (res) {
        return res.value
      }
    },
    /**
     * 时间处理
     */
    formateTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    /**
     * 删除员工
     */
    del(id) {
      this.$confirm('确认删除？', '提示')
        .then(async() => {
          await delEmployeeApi(id)
          this.$message.success('删除成功')
          if (this.list.length === 1 && this.page > 1) {
            this.page = this.page - 1
            this.getEmployeeList()
          }
        })
        .catch(() => {})
    },
    openAddDialog() {
      this.showDialog = true
    },
    /**
     * 导出excel的方法
     */
    handleDownload() {
      import('@/vendor/Export2Excel').then(async(excel) => {
        const headersArr = [
          '姓名',
          '手机号',
          '入职日期',
          '聘用形式',
          '转正日期',
          '工号',
          '部门'
        ]
        const headersRelations = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }
        const res = await getEmployeeListApi(1, this.total)
        const rows = res.data.rows
        const dataArr = this.formatJson(rows, headersArr, headersRelations)
        excel.export_json_to_excel({
          header: headersArr, // 表头
          data: dataArr, // 二维数组，导出的数据
          filename: '员工信息', // 文件名
          autoWidth: true, // 宽度自适应
          bookType: 'xlsx'
        })
      })
    },
    formatJson(rows, headersArr, headersRelations) {
      const dataArr = [] // 要接收的数组
      rows.forEach((item) => {
        const orginArr = []
        headersArr.forEach((header) => {
          const newKey = headersRelations[header]
          let newValue = item[newKey]
          // 改变特定的value数据
          // 改变正式和非正式员工
          if (newKey === 'formOfEmployment') {
            const hireType = EnumObj.hireType
            const result = hireType.find((type) => {
              return +newValue === type.id
            })
            newValue = result ? result.value : '未知'
          }
          // 改变日期，对日期格式化
          if (['correctionTime', 'timeOfEntry'].includes(newKey)) {
            newValue = newValue ? dayjs(newValue).format('YYYY-MM-DD') : ''
          }
          orginArr.push(newValue)
        })
        dataArr.push(orginArr)
      })
      return dataArr
    }
  }
}
</script>

<style>
.img_box{
  width: 150px;
}
</style>
